#include "prime_generator_service.h"

#include <mutex>
#include <string.h>

#include "my_socket_server.h"

const sptr<PrimeGeneratorService> &PrimeGeneratorService::GetInstance()
{
    if (instance == nullptr) {
        static std::mutex mutex;
        std::lock_guard<std::mutex> lock(mutex);
        if (instance == nullptr) {
            instance = new PrimeGeneratorService();
        }
    }
    return instance;
}

int PrimeGeneratorService::GetID()
{
    return 123;
}

std::string PrimeGeneratorService::Process(const std::string &message)
{
    // get开头的
    const char *command = "get ";
    if (message.find(command) == 0) {
        std::string number = message.substr(strlen(command));
        int primeID;
        constexpr int parsingNumber = 1;
        if (sscanf(number.c_str(), "%d", &primeID) != parsingNumber) {
            return "invalid number";
        }

        return ProcessGet(primeID);
    }
    return "invalid";
}

std::string PrimeGeneratorService::ProcessGet(int id)
{
    static int primes[] = {2, 3, 5, 7, 11};
    int prime = 0;
    if (id >= sizeof(primes)) {
        prime = -1;
    } else {
        prime = primes[id];
    }

    char primeString[20];
    snprintf(primeString, sizeof(primeString), "%d", prime);
    return primeString;
}
